#Copyright 2011 Mohit Shah

#This file is part of soundblogs-python.

#soundblogs-python is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.

#soundblogs-python is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with soundblogs-python.  If not, see <http://www.gnu.org/licenses/>.


import scikits.audiolab as ahand
import math
import numpy as np
import scipy.signal as sp

class AudioFile:
    "Read audio file"

    def __init__(self,filename):
        self.file = filename
        alldata = ahand.wavread(filename)
        self.fs = alldata[1]
        self.data = alldata[0]
        self.n = len(self.data)
        self.channels = np.size(self.data[0])
        self.index = 0
        self.overlap = 0
        self.framesize = 1024
        self.numberframes = 0
        self.window = 'hamming'
        if self.channels == 2:
            self.data = (self.data[0:self.n,0]+self.data[0:self.n,1])/2
        else:
            self.data = self.data[0:self.n]
        self.params = {'length':self.n, 'channels':self.channels, 'samplerate':self.fs, 'framesize':self.framesize, 'totalframes':self.numberframes, 'overlap':self.overlap, 'window':self.window}
    
    def setPreEmphasis(self,val):
        if val == 1:
            self.data = sp.lfilter([1,-0.97],1,self.data)
    def setWindow(self,window):
        self.window = window

    def getWindow(self):
        return self.window

    def getParameters(self):
        return self.params

    def setOverlap(self,overlap):
        "Between 0 and 1"
        if overlap >= 1:
            print "Error : Values between 0 and 1 only"
        else:
            self.overlap = overlap

    def getOverlap(self):
        return self.overlap

    def setFrameSize(self,size):
        self.framesize = size

    def getFrameSize(self):
        return self.framesize

    def initFrames(self):
        self.numberframes = math.floor((self.n - math.floor(self.framesize*self.overlap))/(self.framesize - math.floor(self.framesize*self.overlap)))
        return int(self.numberframes)

    def readFrame(self,index):
        temp = self.data[index*math.floor((1-self.overlap)*self.framesize):((index+1)*math.floor((1-self.overlap)*self.framesize))+math.floor(self.overlap*self.framesize)]
        return (sp.get_window(self.window,self.framesize)*temp)

    
